<template>
	<view>
		<view>
			<u-tabs-swiper ref="uTabs" :list="topicCate" active-color="#616161" :current="current" @change="tabsChange"
			 :is-scroll="false" swiperWidth="750"></u-tabs-swiper>
		</view>
		<swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
			<swiper-item v-for="(item1, index1) in topicCate" :key="index1">
				<scroll-view scroll-y style="height: calc(100vh - 80rpx);width: 100%;" @scrolltolower="onreachBottom">
					<u-grid :col="3" :border="false" @click="toTopic">
						<u-grid-item :index="item2.id" v-for="(item2, index2) in topicList" :key="index2">
							<u-image border-radius="10" width="200rpx" height="260rpx" :src="item2.cover_image"></u-image>
							<view class="grid-text">{{item2.topic_name}}</view>
						</u-grid-item>
					</u-grid>
					<!-- 加载状态 -->
					<block v-if="topicList.length === 0 && loadStatus == 'nomore'">
						<u-empty text="暂无相关圈子" mode="favor"></u-empty>
					</block>
					<block v-if="loadStatus != 'none'">
						<u-loadmore :status="loadStatus" />
					</block>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	let page;
	export default {
		data() {
			return {
				current: 0,
				topicCate: [],
				topicCateId: 0,
				topicList: [],
				loadStatus: "loading",
				swiperCurrent: 0, // swiper组件的current值，表示当前那个swiper-item是活动的
			};
		},
		onLoad() {
			page = 1;
			this.getTopicCate();
			this.getTopicList();
		},
		methods: {
			// tabs通知swiper切换
			tabsChange(index) {
				this.swiperCurrent = index;
			},
			// swiper-item左右移动，通知tabs的滑块跟随移动
			transition(e) {
				let dx = e.detail.dx;
				this.$refs.uTabs.setDx(dx);				
			},
			// 由于swiper的内部机制问题，快速切换swiper不会触发dx的连续变化，需要在结束时重置状态
			// swiper滑动结束，分别设置tabs和swiper的状态
			animationfinish(e) {
				let current = e.detail.current;
				this.$refs.uTabs.setFinishCurrent(current);
				this.swiperCurrent = current;
				this.current = current;
				
				page = 1;
				this.topicList = [];
				this.topicCateId = this.topicCate[current].id
				this.getTopicList();
			},
			// scroll-view到底部加载更多
			onreachBottom() {
				page++;
				this.getTopicList();
			},
			getTopicCate() {
				this.$H.post("/api/topic/cateList")
					.then(res => {
						this.topicCate = res[1].data;
					})
			},
			getTopicList() {
				this.loadStatus = "loading";
				this.$H.post('/api/topic/cateTopic/?page=' + page, {
					id: this.topicCateId
				}).then(res => {
					this.topicList = this.topicList.concat(res[1].data.data);
					if (res[1].data.current_page === res[1].data.last_page || res[1].data.last_page === 0) {
						this.loadStatus = "nomore";
					} else {
						this.loadStatus = "loadmore"
					}
				})
			},
			toTopic(id){
				uni.navigateTo({
					url:"/pages/topic-detail/topic-detail?id=" + id
				})
			}
		}
	}
</script>

<style lang="scss">
	@import 'topic-list.css';
</style>
